package com.ml4ai.backend.sys;

import com.ml4ai.backend.services.CacheService;
import com.ml4ai.backend.utils.ObjUtil;
import com.ml4ai.backend.utils.StringHelper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.session.SessionRepository;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by leecheng on 2017/11/9.
 */
@Component
public class ExtSessionRepository implements SessionRepository<ExtSession> {

    @Autowired
    private CacheService cacheService;

    @Override
    public ExtSession createSession() {
        String sessionId = StringHelper.uuid();
        Map<String, Object> session = new LinkedHashMap<>();
        long current = System.currentTimeMillis();
        return new ExtSession(sessionId, session, current, current, 300);
    }

    @Override
    @SneakyThrows
    public void save(ExtSession session) {
        String val = ObjUtil.obj2str(session);
        cacheService.put("SESSION_STORE", session.getId(), val);
    }

    @Override
    @SneakyThrows
    public ExtSession getSession(String id) {
        try {
            String val = (String) cacheService.get("SESSION_STORE", id);
            if (val == null) {
                return null;
            } else {
                return (ExtSession) ObjUtil.str2obj(val);
            }
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public void delete(String id) {
        cacheService.delete("SESSION_STORE", id);
    }


}